package atbash

import (
	"regexp"
	"strings"
)

const testVersion = 2

const plain = "abcdefghijklmnopqrstuvwxyz"
const cipher = "zyxwvutsrqponmlkjihgfedcba"

func Atbash(input string) string {
	s := strings.ToLower(input)

	reg := regexp.MustCompile(`[a-z0-9]`)
	plainArray := reg.FindAllString(s, -1)

	cipherArray := make([]string, len(plainArray)+len(plainArray)/5+1)
	cipherIdx := 0
	step := 0

	for i := 0; i < len(plainArray); i++ {

		if idx := strings.Index(plain, plainArray[i]); idx == -1 {
			cipherArray[cipherIdx] = plainArray[i]
		} else {
			cipherArray[cipherIdx] = cipher[idx : idx+1]
		}

		// add space
		cipherIdx++
		step++
		if step == 5 {
			cipherArray[cipherIdx] = " "
			cipherIdx++
			step = 0
		}
	}

	return strings.TrimRight(strings.Join(cipherArray, ""), " ")
}
